package cn.deepmax.anime.web.task;

import cn.deepmax.anime.web.Constant;
import cn.deepmax.anime.web.pojo.Section;
import cn.deepmax.anime.web.pojo.SectionImg;
import cn.deepmax.anime.web.redis.RedisTemplate;
import cn.deepmax.anime.web.support.WebDriverPool;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.io.File;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class SectionPageTask extends SectionTotalTask{

    private Integer page;
    private File file;

    public SectionPageTask(Section section, WebDriverPool<? extends WebDriver> pool, RedisTemplate redisTemplate, CountDownLatch latch, Integer page) {
        super(section, pool, redisTemplate, latch);
        this.page = page;

    }

    @Override
    public void runInternal() {
        String key = Constant.getPageKey(section.getIndex(), page);
        SectionImg img = redisTemplate.get(key, SectionImg.class);
        if(img==null){
            WebDriver driver = null;
            try{
                driver = pool.getResource();
                String url = section.getUrl()+"?page="+page;
                driver.get(url);
                WebElement imgTag = driver.findElement(By.id("viewimg"));
                String picUrl = imgTag.getAttribute("src");
                if(picUrl!=null||picUrl.length()!=0){
                    img = new SectionImg();
                    img.setPage(page);
                    img.setUrl(picUrl);
                    img.setSectionIndex(section.getIndex());
                    redisTemplate.set(key, img);
                    log.info("Found img url [S{}][P{}][{}]",section.getIndex(), page, picUrl);
                }else{
                    log.error("Unable to found url of [S{}][P{}]", section.getIndex(), page);
                }
            }finally {
                if(driver!=null){
                    pool.returnResource(driver);
                }
            }
        }
        SectionImg newImg = redisTemplate.get(key, SectionImg.class);
        if(newImg.getUrl()==null){
            throw new IllegalStateException("Impossible null url: "+newImg.getSectionIndex()+" "+newImg.getPage());
        }
        DownLoadTask task = new DownLoadTask(newImg);
        task.run();
        latch.countDown();
    }



}
